# -*- encoding: utf-8 -*-
"""
File Name: monitor_pipline_util
Description: Utility functions for monitoring pipeline using Zabbix.
Author : 'lirui'
Date: 10/24/2024
Contact: marjey_lee@163.com
Change Activity:
10/24/2024:
"""
from modules.blk.cmdb.cmdb_service import CMDBService
from modules.zabbix_utils.utils.zabbix_client import ZabbixClient
from projects.monitoring.zabbix_monitoring.config.config import ZABBIX_USERNAME, ZABBIX_PASSWORD


def load_zabbix_docker_info_from_cmdb():
    """
    Load Zabbix Docker information from CMDB.

    Returns:
        dict: A dictionary containing Zabbix Docker information.
    """
    data = CMDBService().select('zabbix_docker_info')
    return data['data']['info']


def _filter_recovered_problems(problems):
    """
    Filter out recovered problems from the list of problems.

    Args:
        problems (list): A list of problems.

    Returns:
        list: A list of problems that are not recovered.
    """
    ps = []
    for p in problems:
        if p['r_eventid'] == '0':
            ps.append(p)
    return ps


def _get_problems_from_one_zabbix_server(client: ZabbixClient):
    """
    Get problems from one Zabbix server.

    Args:
        client (ZabbixClient): An instance of ZabbixClient.

    Returns:
        list: A list of problems from the Zabbix server.
    """
    t = client.get_template('problems', 'hosts_with_problems')
    hosts = client.fetch(t)
    if len(hosts) == 0:
        return []
    problem_res = []
    for host in hosts:
        t = client.get_template('problems', 'get')
        t['params']['hostids'] = host['hostid']
        problems = client.fetch(t)
        problems = _filter_recovered_problems(problems)
        for problem in problems:
            problem['zabbix_ip'] = client.ip
            problem['zabbix_port'] = client.port
            problem['hostid'] = host['hostid']
            problem['host_name'] = host['name']
        problem_res.extend(problems)
    return problem_res


def get_one_zabbix_server_problems(info):
    """
    Load problems from one Zabbix server.

    Args:
        info (dict): A dictionary containing Zabbix server information.

    Returns:
        list: A list of problems from the Zabbix server.
    """
    client = ZabbixClient(
        ip=info['docker_server_ip'],
        port=info['docker_server_port'],
        username=ZABBIX_USERNAME,
        password=ZABBIX_PASSWORD
    )
    problems = _get_problems_from_one_zabbix_server(client)
    return problems
